package com.yanqu.road.server.manager.activity.feast.activity;

import com.google.protobuf.AbstractMessage;
import com.yanqu.road.dao.impl.activity.feast.FeastConfigDaoImpl;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.feast.config.ShanHeFeastConfig;
import com.yanqu.road.entity.activity.feast.pvp.Coordinate;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityInfoMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.UUIDHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 配置相关
 */
public class CrossFeastBaseActivity {

    protected static Logger logger = LogManager.getLogger(CrossFeastBaseActivity.class.getName());

    /**
     * 锁
     */
    protected final Object lock = new Object();

    /**
     * 随机
     */
    protected static RandomHelper randomHelper = new RandomHelper();

    /**
     * 活动配置
     */
    protected ShanHeFeastConfig config;

    /**
     * 榜单长度
     */
    protected int userMaxRankConfig = 1000;


    public CrossFeastBaseActivity(ActivityInfo activityInfo) {
        // 读配置
        loadConfigFromDb(activityInfo);
    }

    public void loadConfigFromDb(ActivityInfo activityInfo) {
        initMaxRankConfig(activityInfo.getActivityId());

        Map<String, ActivityConfig> activityConfigMap = ActivityBussiness.getActivityConfigMap(Collections.singletonList(activityInfo.getActivityId())).get(activityInfo.getActivityId());
        // 读配置
        ShanHeFeastConfig tmpConfig = new ShanHeFeastConfig();
        FeastConfigDaoImpl configDao = new FeastConfigDaoImpl();
        tmpConfig.setActivityInfo(ActivityBussiness.getActivityInfoByActivityId(activityInfo.getActivityId()));
        tmpConfig.setPlaceConfigMap(configDao.getFeastPvpPlaceConfigMap(activityInfo.getActivityId()));
        tmpConfig.setEquipmentConfigMap(configDao.getFeastEquipmentConfigMap(activityInfo.getActivityId()));
        tmpConfig.setEventConfigMap(configDao.getFeastEventConfigMap(activityInfo.getActivityId()));
        tmpConfig.setMissionConfigMap(configDao.getFeastMissionMap(activityInfo.getActivityId()));
        tmpConfig.setStateConfigMap(configDao.getFeastStateConfigMap(activityInfo.getActivityId()));
        tmpConfig.setTripodConfigMap(configDao.getFeastTripodConfigMap(activityInfo.getActivityId()));
        tmpConfig.setNpcConfigMap(configDao.getFeastNpcConfigMap(activityInfo.getActivityId()));
        tmpConfig.initConfig(activityConfigMap);
        config = tmpConfig;
    }

    public ShanHeFeastConfig getConfig() {
        return config;
    }

    private void initMaxRankConfig(int activityId) {
        List<ActivityConditionInfo> conditionInfoList = ActivityInfoMgr.getConditionInfoList(activityId, eGamePlayerEventType.FeastPersonalScoreRank.getValue());
        if(conditionInfoList != null){
            userMaxRankConfig = getMaxRankConfig(conditionInfoList);
        }
    }

    private int getMaxRankConfig(List<ActivityConditionInfo> list) {
        int maxRank = 0;
        for (ActivityConditionInfo conditionInfo : list) {
            int tmp = conditionInfo.getParamList().get(1).intValue();
            if (tmp > 0 && maxRank < tmp) {
                maxRank = tmp;
            }
        }
        return maxRank;
    }


    protected void sendPacket(int code, AbstractMessage.Builder<?> messageBuilder, long userId) {
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
        if (userBaseInfo == null) {
            return;
        }
        YanQuMessage message = YanQuMessageUtils.buildMessage(code, messageBuilder);
        MessageHelper.sendPacket(userBaseInfo.getServerId(), userId, message);
    }

    protected void sendPacket(long serverId, int code, AbstractMessage.Builder<?> messageBuilder, long userId) {
        YanQuMessage message = YanQuMessageUtils.buildMessage(code, messageBuilder);
        MessageHelper.sendPacket(serverId, userId, message);
    }

    protected void sendPacketToAll(int code, AbstractMessage.Builder<?> messageBuilde, Collection<Long> userIdList) {
        MessageHelper.sendPacketToAll(code, messageBuilde, userIdList);
//        ShanHeFeastProto.FeastAgentTransferMsg.Builder agentMsg = ShanHeFeastProto.FeastAgentTransferMsg.newBuilder();
//        agentMsg.setCode(code);
//        agentMsg.addAllUserId(userIdList);
//        agentMsg.setMsg(messageBuilde.build().toByteString());
//
//        YanQuMessage message = YanQuMessageUtils.buildMessage(AgentProtocol.A_SHAN_HE_FEASTS_TRANSFER, agentMsg);
//        for (Long serverId : config.getActivityInfo().getServerIdList()) {
//            //todo
//            if(serverId == 99938028L){
//                continue;
//            }
//            MessageHelper.sendPacket(serverId, 0, message);
//        }
    }

    /**
     * 获取大于等于给定值的最小的n的2次方的值
     */
    protected static int getNextSquare(int value) {
        int n = 0;
        while (Math.pow(n, 2) < value) {
            n++;
        }
        return (int) Math.pow(n, 2);
    }

    protected static String randomUUID(){
        return UUIDHelper.randomUUID("dm");
    }

    /**
     * 获取圆内随机一点的坐标
     *
     * @param x x轴
     * @param y y轴
     * @param r 半径
     */
    protected static Coordinate generateRandomCoordinate(double x, double y, double r) {
        double angle = Math.toRadians(randomHelper.next(0, 360));
        double radius = r * Math.sqrt(randomHelper.nextDouble(0, 1));
        return new Coordinate(x + radius * Math.cos(angle), y + radius * Math.sin(angle));
    }

    /**
     * 判断两点的距离
     */
    protected double distance(Coordinate coordinate1, Coordinate coordinate2) {
        return Math.sqrt(Math.pow(coordinate2.getX() - coordinate1.getX(), 2) + Math.pow(coordinate2.getY() - coordinate1.getY(), 2));
    }

    /**
     * 计算方向向量
     * @param coordinate1   原
     * @param coordinate2   目标
     * @return
     */
    protected Coordinate calcDirection(Coordinate coordinate1, Coordinate coordinate2) {
        double dx = coordinate2.getX() - coordinate1.getX();
        double dy = coordinate2.getY() - coordinate1.getY();

        // 归一化处理
        double mag = Math.sqrt(dx * dx + dy * dy);
        return new Coordinate(dx / mag, dy / mag);
    }

}
